#include "widget_funcb_smart_vision.h"
#include "ui_widget_funcb_smart_vision.h"
#include <QPainter>
#include <QStateMachine>
#include <QSignalTransition>
#include <QSslSocket>
#include <QHostAddress>
#include <QTimer>
#include <QTextCodec>

Widget_funcB_Smart_vision::Widget_funcB_Smart_vision(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget_funcB_Smart_vision),
    tcpSocket(new QTcpSocket(this)),
    // 初始化动态图播放器
    gifMovie(new QMovie(this))
{
    ui->setupUi(this);

    // 在构造函数中统一设置样式
    QString style = R"(
        QWidget#widget { background-color: #F6FAFE; }
        QLabel { border: none; } /* 去除标签边框 */
    )";
    this->setStyleSheet(style);

    ui->label_return_home->setPixmap(QPixmap(":/img/home_start_close.png"));
    ui->label_run_home->setPixmap(QPixmap(":/img/home_start_open.png"));
    ui->label_getup->setPixmap(QPixmap(":/img/home_start_open.png"));
    ui->label_sleep->setPixmap(QPixmap(":/img/home_start_close.png"));
    ui->label_a1->setPixmap(QPixmap(":/img/home_start_close.png"));
    ui->label_a2->setPixmap(QPixmap(":/img/home_start_close.png"));
    ui->label_a3->setPixmap(QPixmap(":/img/home_start_close.png"));
    ui->label_a4->setPixmap(QPixmap(":/img/home_start_close.png"));
    ui->label_a5->setPixmap(QPixmap(":/img/home_start_close.png"));
    ui->label_a6->setPixmap(QPixmap(":/img/home_start_close.png"));


    QPixmap homePixmap(":/img/home1.png");
    ui->label_return_home_2->setPixmap(homePixmap.scaled(40, 40, Qt::KeepAspectRatio, Qt::SmoothTransformation));

    QPixmap outPixmap(":/img/home_out.png");
    ui->label_h2->setPixmap(outPixmap.scaled(40, 40, Qt::KeepAspectRatio, Qt::SmoothTransformation));

    QPixmap getupPixmap(":/img/getup.png");
    ui->label_up->setPixmap(getupPixmap.scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));

    QPixmap sleepPixmap(":/img/sleep.png");
    ui->label_sleep_2->setPixmap(sleepPixmap.scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));

    QPixmap ktPixmap(":/img/kt.png");
    ui->label_kt->setPixmap(ktPixmap.scaled(50, 50, Qt::KeepAspectRatio, Qt::SmoothTransformation));

    QPixmap tvPixmap(":/img/tv.png");
    ui->label_tv->setPixmap(tvPixmap.scaled(50, 50, Qt::KeepAspectRatio, Qt::SmoothTransformation));

    QPixmap robotPixmap(":/img/robot.png");
    ui->label_rb->setPixmap(robotPixmap.scaled(40, 40, Qt::KeepAspectRatio, Qt::SmoothTransformation));

    QPixmap breadPixmap(":/img/bread.png");
    ui->label_bread->setPixmap(breadPixmap.scaled(40, 40, Qt::KeepAspectRatio, Qt::SmoothTransformation));

    QPixmap clothPixmap(":/img/cloth.png");
    ui->label_cloth->setPixmap(clothPixmap.scaled(40, 40, Qt::KeepAspectRatio, Qt::SmoothTransformation));

    QPixmap wifiPixmap(":/img/WIFI.png");
    ui->label_wifi->setPixmap(wifiPixmap.scaled(50, 50, Qt::KeepAspectRatio, Qt::SmoothTransformation));


    // 连接按钮信号
    connect(ui->label_return_home , &Button_home_start::signals_start , this , &Widget_funcB_Smart_vision::slots_button_start);
    connect(ui->label_run_home , &Button_home_start::signals_start , this , &Widget_funcB_Smart_vision::slots_button_start);
    // 在构造函数中添加信号连接
    connect(ui->label_getup, &Button_home_start::signals_start, this, &Widget_funcB_Smart_vision::slots_button_getup);
    connect(ui->label_sleep, &Button_home_start::signals_start, this, &Widget_funcB_Smart_vision::slots_button_getup);
    // 连接设备按钮信号
    connect(ui->label_a1, &Button_home_start::signals_start, this, [this](bool start) {
        ui->label_a1->set_start(start); // 空调开关状态切换
    });

    // ========== 动态图初始化 ==========
    // 设置动态图文件路径（替换为你的 GIF 动图路径）
    gifMovie->setFileName(":/img/dog.gif");
    // 将动态图设置到右下角 label（假设右下角 label 为 ui->label_bottom_right）
    ui->label_bottom_right->setMovie(gifMovie);
    // 启动动态图播放
    gifMovie->start();

    // ====================== 连接按钮点击信号与槽函数 ======================
    // 场景按钮：归家
    connect(ui->label_return_home, &Button_home_start::signals_start, this, [this](bool start) {
        ui->label_return_home->setPixmap(QPixmap(start ? ":/img/home_start_open.png" : ":/img/home_start_close.png"));
        // 若需要，可在此添加 TCP 发送逻辑，通知其他设备“归家”状态
        sendMessage(start ? "归家 开" : "归家 关");
    });

    // 场景按钮：离家
    connect(ui->label_run_home, &Button_home_start::signals_start, this, [this](bool start) {
        ui->label_run_home->setPixmap(QPixmap(start ? ":/img/home_start_open.png" : ":/img/home_start_close.png"));
        sendMessage(start ? "离家 开" : "离家 关");
    });

    // 场景按钮：起床
    connect(ui->label_getup, &Button_home_start::signals_start, this, [this](bool start) {
        ui->label_getup->setPixmap(QPixmap(start ? ":/img/home_start_open.png" : ":/img/home_start_close.png"));
        sendMessage(start ? "起床 开" : "起床 关");
    });

    // 场景按钮：睡觉
    connect(ui->label_sleep, &Button_home_start::signals_start, this, [this](bool start) {
        ui->label_sleep->setPixmap(QPixmap(start ? ":/img/home_start_open.png" : ":/img/home_start_close.png"));
        sendMessage(start ? "睡觉 开" : "睡觉 关");
    });

    // 设备按钮：空调
    connect(ui->label_a1, &Button_home_start::signals_start, this, [this](bool start) {
        ui->label_a1->setPixmap(QPixmap(start ? ":/img/home_start_open.png" : ":/img/home_start_close.png"));
        sendMessage(start ? "空调 开" : "空调 关");
    });

    // 设备按钮：电视
    connect(ui->label_a2, &Button_home_start::signals_start, this, [this](bool start) {
        ui->label_a2->setPixmap(QPixmap(start ? ":/img/home_start_open.png" : ":/img/home_start_close.png"));
        sendMessage(start ? "电视 开" : "电视 关");
    });

    // 设备按钮：机器人
    connect(ui->label_a3, &Button_home_start::signals_start, this, [this](bool start) {
        ui->label_a3->setPixmap(QPixmap(start ? ":/img/home_start_open.png" : ":/img/home_start_close.png"));
        sendMessage(start ? "机器人 开" : "机器人 关");
    });

    // 设备按钮：烤面包机
    connect(ui->label_a4, &Button_home_start::signals_start, this, [this](bool start) {
        ui->label_a4->setPixmap(QPixmap(start ? ":/img/home_start_open.png" : ":/img/home_start_close.png"));
        sendMessage(start ? "烤面包机 开" : "烤面包机 关");
    });

    // 设备按钮：洗衣机
    connect(ui->label_a5, &Button_home_start::signals_start, this, [this](bool start) {
        ui->label_a5->setPixmap(QPixmap(start ? ":/img/home_start_open.png" : ":/img/home_start_close.png"));
        sendMessage(start ? "洗衣机 开" : "洗衣机 关");
    });

    // 设备按钮：WIFI
    connect(ui->label_a6, &Button_home_start::signals_start, this, [this](bool start) {
        ui->label_a6->setPixmap(QPixmap(start ? ":/img/home_start_open.png" : ":/img/home_start_close.png"));
        sendMessage(start ? "WIFI 开" : "WIFI 关");
    });

    // --- ✅ 新增：TCP 客户端初始化 ---
   tcpSocket = new QTcpSocket(this);
   connect(tcpSocket, &QTcpSocket::readyRead, this, &Widget_funcB_Smart_vision::onReadyRead);
   connect(tcpSocket, &QTcpSocket::disconnected, this, &Widget_funcB_Smart_vision::onDisconnected);
   connectToServer();

}

Widget_funcB_Smart_vision::~Widget_funcB_Smart_vision()
{
    delete ui;
}

void Widget_funcB_Smart_vision::slots_button_start(bool start)
{
    QObject * temp = sender();
    // 离开
    if(temp == ui->label_run_home)
    {
        // 离家开
        ui->label_run_home->set_start(start);
        // 归家关
        ui->label_return_home->set_start(!start);
    }
    // 归家
    if(temp == ui->label_return_home)
    {
        // 离家开
        ui->label_return_home->set_start(start);
        // 归家关
        ui->label_run_home->set_start(!start);
    }
}

void Widget_funcB_Smart_vision::slots_button_send_message()
{
    // 增加一个widget  内部包含
    QWidget *newWidget = new QWidget(this);
    QVBoxLayout *layout = new QVBoxLayout(newWidget);
    QLabel *label = new QLabel("这是新增的内容", newWidget);
    layout->addWidget(label);
    // 将 newWidget 添加到当前窗口的某个布局中，比如主布局
    QVBoxLayout *mainLayout = qobject_cast<QVBoxLayout*>(this->layout());
    if (mainLayout) {
        mainLayout->insertWidget(1, newWidget); // 插入到索引1的位置，避免放在末尾
    }
}
// 实现起床场景切换槽函数
void Widget_funcB_Smart_vision::slots_button_getup(bool start)
{
    QObject * temp1 = sender();
    if(temp1 == ui->label_getup)
    {
        ui->label_getup->set_start(start);
        ui->label_sleep->set_start(!start);
    }
    if(temp1 == ui->label_sleep)
    {
        ui->label_sleep->set_start(start);
        ui->label_getup->set_start(!start);
    }
}

void Widget_funcB_Smart_vision::slots_button_sleep(bool start)
{
    // 这里编写“睡眠”按钮相关的逻辑，比如切换图片、控制设备等
    qDebug() << "Sleep button state:" << start;
}

void Widget_funcB_Smart_vision::connectToServer()
{
    if (tcpSocket->state() == QAbstractSocket::ConnectedState)
        return;

    qDebug() << "正在连接服务器..." << serverIP << ":" << serverPort;
    tcpSocket->connectToHost(QHostAddress(serverIP), serverPort);

    if (!tcpSocket->waitForConnected(3000)) {
        qDebug() << "连接服务器失败：" << tcpSocket->errorString();
    } else {
        qDebug() << "已连接服务器";
    }
}

void Widget_funcB_Smart_vision::onDisconnected()
{
    qDebug() << "服务器连接断开，尝试重连...";
    QTimer::singleShot(2000, this, &Widget_funcB_Smart_vision::connectToServer);
}

void Widget_funcB_Smart_vision::sendMessage(const QString &msg)
{
    if (tcpSocket->state() != QAbstractSocket::ConnectedState) {
        connectToServer();
        qDebug() << "服务器未连接，正在重连...";
        return;
    }

       QTextCodec *codec = QTextCodec::codecForName("GBK");  // 转GBK编码
       QByteArray data = codec->fromUnicode(msg + "\r\n");    // 加上换行，调试助手友好显示
       tcpSocket->write(data);
       tcpSocket->flush();
    qDebug() << "已发送消息：" << msg;
}

void Widget_funcB_Smart_vision::onReadyRead()
{
    QByteArray data = tcpSocket->readAll();
    QTextCodec *codec = QTextCodec::codecForName("GBK");  // 按GBK解析
    QString msg = codec->toUnicode(data).trimmed();

    handleReceivedCommand(msg);
}

void Widget_funcB_Smart_vision::handleReceivedCommand(const QString &msg)
{
    QString text = msg;
    text.replace("\r", "").replace("\n", "").replace(" ", "");

    qDebug() << "处理指令:" << text;

    bool isOn = false;
    // 判断指令是“开”还是“关”
    if (text.contains(QRegExp("开|开启"))) {
        isOn = true;
    } else if (text.contains(QRegExp("关|关闭"))) {
        isOn = false;
    } else {
        // 既不是开也不是关，直接返回或做其他处理
        qDebug() << "指令不是开/关类型";
        return;
    }

    // 根据 isOn 切换对应设备的图片
    if (text.contains("空调")) {
        ui->label_a1->setPixmap(QPixmap(isOn ? ":/img/home_start_open.png" : ":/img/home_start_close.png"));
    } else if (text.contains("电视")) {
        ui->label_a2->setPixmap(QPixmap(isOn ? ":/img/home_start_open.png" : ":/img/home_start_close.png"));
    } else if (text.contains("机器人")) {
        ui->label_a3->setPixmap(QPixmap(isOn ? ":/img/home_start_open.png" : ":/img/home_start_close.png"));
    } else if (text.contains("烤面包机")) {
        ui->label_a4->setPixmap(QPixmap(isOn ? ":/img/home_start_open.png" : ":/img/home_start_close.png"));
    } else if (text.contains("洗衣机")) {
        ui->label_a5->setPixmap(QPixmap(isOn ? ":/img/home_start_open.png" : ":/img/home_start_close.png"));
    } else if (text.contains("WIFI") || text.contains("wifi")) {
        ui->label_a6->setPixmap(QPixmap(isOn ? ":/img/home_start_open.png" : ":/img/home_start_close.png"));
    } else {
        qDebug() << "未匹配到已知设备";
    }
}
